<template>
  <div class="drive-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><OfficeBuilding /></el-icon>
          <div class="header-text">
            <h2>公司网盘</h2>
            <p>团队共享文件存储空间</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="showUploadDialog = true">
            <el-icon><Upload /></el-icon>
            上传文件
          </el-button>
          <el-button type="primary" @click="showFolderDialog = true">
            <el-icon><Plus /></el-icon>
            新建文件夹
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 存储空间信息 -->
    <el-card shadow="never" class="storage-card">
      <div class="storage-info">
        <div class="storage-item">
          <el-icon><Folder /></el-icon>
          <span>已使用：{{ storageInfo.used }} / {{ storageInfo.total }}</span>
        </div>
        <el-progress :percentage="storageInfo.percentage" :color="storageInfo.percentage > 80 ? '#f56c6c' : '#67c23a'" />
      </div>
    </el-card>

    <!-- 面包屑导航 -->
    <el-card shadow="never" class="breadcrumb-card">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/drive/company' }">
          <el-icon><House /></el-icon>
          公司网盘
        </el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item, index) in currentPath" :key="index">
          {{ item }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧文件夹树 -->
      <el-col :span="5">
        <el-card shadow="never" class="tree-card">
          <div class="tree-header">
            <el-icon><FolderOpened /></el-icon>
            <span>文件夹</span>
          </div>
          <el-tree
            :data="folderTree"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-icon><Folder /></el-icon>
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧文件列表 -->
      <el-col :span="19">
        <el-card shadow="never">
          <!-- 工具栏 -->
          <div class="toolbar">
            <el-input
              v-model="searchText"
              placeholder="搜索文件或文件夹"
              clearable
              style="width: 300px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <div class="toolbar-right">
              <el-radio-group v-model="viewMode">
                <el-radio-button label="grid">
                  <el-icon><Grid /></el-icon>
                </el-radio-button>
                <el-radio-button label="list">
                  <el-icon><List /></el-icon>
                </el-radio-button>
              </el-radio-group>
              <el-select v-model="sortBy" placeholder="排序方式" style="width: 150px">
                <el-option label="名称" value="name" />
                <el-option label="修改时间" value="time" />
                <el-option label="大小" value="size" />
                <el-option label="类型" value="type" />
              </el-select>
            </div>
          </div>

          <!-- 网格视图 -->
          <div v-if="viewMode === 'grid'" class="grid-view">
            <div
              v-for="item in filteredFiles"
              :key="item.id"
              class="grid-item"
              @click="handleItemClick(item)"
              @contextmenu.prevent="handleContextMenu(item, $event)"
            >
              <div class="item-icon">
                <el-icon :size="60" :color="getFileColor(item.type)">
                  <component :is="getFileIcon(item.type)" />
                </el-icon>
              </div>
              <div class="item-name" :title="item.name">{{ item.name }}</div>
              <div class="item-info">
                <span class="item-size">{{ item.size }}</span>
                <span class="item-time">{{ item.time }}</span>
                <span class="item-owner">{{ item.owner }}</span>
              </div>
            </div>
          </div>

          <!-- 列表视图 -->
          <el-table v-else :data="filteredFiles" stripe>
            <el-table-column type="selection" width="55" />
            <el-table-column label="名称" min-width="250">
              <template #default="{ row }">
                <div class="file-name" @click="handleItemClick(row)">
                  <el-icon :size="24" :color="getFileColor(row.type)">
                    <component :is="getFileIcon(row.type)" />
                  </el-icon>
                  <span class="name-text">{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120" />
            <el-table-column prop="owner" label="上传者" width="120" />
            <el-table-column prop="time" label="修改时间" width="180" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleDownload(row)">
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button link type="success" @click="handleShare(row)">
                  <el-icon><Share /></el-icon>
                  分享
                </el-button>
                <el-button link type="warning" @click="handleRename(row)" v-if="row.owner === currentUser">
                  <el-icon><Edit /></el-icon>
                  重命名
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" v-if="row.owner === currentUser">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-if="filteredFiles.length === 0" description="暂无文件" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 上传文件对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文件" width="600px">
      <el-upload
        drag
        multiple
        :auto-upload="false"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传文档、图片、视频等多种格式
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpload">确定上传</el-button>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog v-model="showFolderDialog" title="新建文件夹" width="500px">
      <el-form :model="folderForm" label-width="100px">
        <el-form-item label="文件夹名称">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFolderDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateFolder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="showShareDialog" title="分享文件" width="500px">
      <el-form :model="shareForm" label-width="100px">
        <el-form-item label="文件名称">
          <el-input v-model="shareForm.fileName" disabled />
        </el-form-item>
        <el-form-item label="分享方式">
          <el-radio-group v-model="shareForm.type">
            <el-radio label="link">链接分享</el-radio>
            <el-radio label="user">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="shareForm.type === 'user'" label="选择用户">
          <el-select v-model="shareForm.users" multiple placeholder="请选择用户" style="width: 100%">
            <el-option label="张三" value="zhangsan" />
            <el-option label="李四" value="lisi" />
            <el-option label="王五" value="wangwu" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="shareForm.type === 'link'" label="分享链接">
          <el-input v-model="shareForm.link" readonly>
            <template #append>
              <el-button @click="copyLink">复制</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showShareDialog = false">取消</el-button>
        <el-button type="primary" @click="handleShareConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  OfficeBuilding, Upload, Plus, House, Folder, FolderOpened, Search, Grid, List,
  Download, Edit, Delete, UploadFilled, Share, Document, Picture, VideoPlay
} from '@element-plus/icons-vue'

// 状态
const searchText = ref('')
const viewMode = ref('grid')
const sortBy = ref('name')
const currentPath = ref([])
const currentUser = ref('当前用户')

// 对话框
const showUploadDialog = ref(false)
const showFolderDialog = ref(false)
const showShareDialog = ref(false)

// 存储信息
const storageInfo = reactive({
  used: '156.8 GB',
  total: '500 GB',
  percentage: 31
})

// 表单
const folderForm = reactive({
  name: ''
})

const shareForm = reactive({
  fileName: '',
  type: 'link',
  users: [],
  link: ''
})

// 文件夹树
const folderTree = ref([
  {
    id: 1,
    name: '公司文件',
    children: [
      { id: 11, name: '项目文档' },
      { id: 12, name: '会议记录' },
      { id: 13, name: '培训资料' },
      { id: 14, name: '制度文件' }
    ]
  },
  {
    id: 2,
    name: '部门文件',
    children: [
      { id: 21, name: '技术部' },
      { id: 22, name: '市场部' },
      { id: 23, name: '人事部' }
    ]
  },
  {
    id: 3,
    name: '公共资源',
    children: []
  }
])

// 文件数据
const files = ref([
  {
    id: 1,
    name: '项目需求文档.docx',
    type: 'word',
    size: '2.5 MB',
    owner: '张三',
    time: '2024-01-15 10:30'
  },
  {
    id: 2,
    name: '公司Logo.png',
    type: 'image',
    size: '1.2 MB',
    owner: '李四',
    time: '2024-01-14 15:20'
  },
  {
    id: 3,
    name: '财务报表.xlsx',
    type: 'excel',
    size: '3.8 MB',
    owner: '王五',
    time: '2024-01-13 09:00'
  },
  {
    id: 4,
    name: '产品宣传片.mp4',
    type: 'video',
    size: '125.6 MB',
    owner: '赵六',
    time: '2024-01-12 14:30'
  },
  {
    id: 5,
    name: '员工手册.pdf',
    type: 'pdf',
    size: '5.2 MB',
    owner: '张三',
    time: '2024-01-11 16:00'
  }
])

// 计算属性
const filteredFiles = computed(() => {
  let result = files.value
  if (searchText.value) {
    result = result.filter(file =>
      file.name.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  // 排序
  result = [...result].sort((a, b) => {
    if (sortBy.value === 'name') return a.name.localeCompare(b.name)
    if (sortBy.value === 'time') return new Date(b.time) - new Date(a.time)
    return 0
  })
  return result
})

// 方法
const handleNodeClick = (data) => {
  console.log('点击文件夹', data)
}

const handleItemClick = (item) => {
  if (item.type === 'folder') {
    currentPath.value.push(item.name)
  } else {
    ElMessage.info('打开文件：' + item.name)
  }
}

const handleContextMenu = (item, event) => {
  console.log('右键菜单', item, event)
}

const handleFileChange = (file, fileList) => {
  console.log('文件变化', file, fileList)
}

const handleUpload = () => {
  ElMessage.success('上传成功')
  showUploadDialog.value = false
}

const handleCreateFolder = () => {
  if (!folderForm.name) {
    ElMessage.warning('请输入文件夹名称')
    return
  }
  ElMessage.success('创建成功')
  showFolderDialog.value = false
  folderForm.name = ''
}

const handleDownload = (row) => {
  ElMessage.success('开始下载：' + row.name)
}

const handleShare = (row) => {
  shareForm.fileName = row.name
  shareForm.link = `https://drive.company.com/share/${row.id}`
  showShareDialog.value = true
}

const handleShareConfirm = () => {
  ElMessage.success('分享成功')
  showShareDialog.value = false
}

const copyLink = () => {
  navigator.clipboard.writeText(shareForm.link).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  })
}

const handleRename = (row) => {
  ElMessageBox.prompt('请输入新名称', '重命名', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.name
  }).then(({ value }) => {
    row.name = value
    ElMessage.success('重命名成功')
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = files.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      files.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const getFileIcon = (type) => {
  const map = {
    folder: Folder,
    word: Document,
    excel: Document,
    pdf: Document,
    image: Picture,
    video: VideoPlay
  }
  return map[type] || Document
}

const getFileColor = (type) => {
  const map = {
    folder: '#409EFF',
    word: '#2B579A',
    excel: '#207245',
    pdf: '#F40F02',
    image: '#67C23A',
    video: '#E6A23C'
  }
  return map[type] || '#909399'
}
</script>

<style scoped>
.drive-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.storage-card {
  margin-bottom: 20px;
}

.storage-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.storage-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.breadcrumb-card {
  margin-bottom: 20px;
}

.tree-card {
  height: calc(100vh - 400px);
  overflow-y: auto;
}

.tree-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  margin-bottom: 16px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  min-height: 400px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.grid-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.item-icon {
  margin-bottom: 12px;
}

.item-name {
  font-size: 14px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  margin-bottom: 8px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.item-owner {
  color: #909399;
  font-size: 11px;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.file-name:hover .name-text {
  color: #409EFF;
  text-decoration: underline;
}
</style>

